package com.dikar.springConsole.jmx;

import java.util.Iterator;
import java.util.LinkedHashMap;

import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;

import org.springframework.jmx.export.naming.ObjectNamingStrategy;

public class AllBeanObjectNamingStrategy implements ObjectNamingStrategy {
	
	private static final String DOMAIN = "spring";
	
	private static final String DEFAULT_PACKAGE ="default";
	
	private static final String KEY_PACKAGE = "package";
	
	private static final String KEY_CLASS = "class";
	
	private static final String KEY_BEAN = "bean";
	
	public ObjectName getObjectName(Object managedBean, String beanKey)
			throws MalformedObjectNameException {
		String packageName = "";
		Package packageObj = managedBean.getClass().getPackage();
		if (packageObj == null) {
			packageName = DEFAULT_PACKAGE;
		}else {
			packageName = packageObj.getName();
		}
		String className = managedBean.getClass().getSimpleName();
		LinkedHashMap<String, String> lhm = new LinkedHashMap<String, String>();

		lhm.put(KEY_PACKAGE, packageName);
		lhm.put(KEY_CLASS, className);
		lhm.put(KEY_BEAN, beanKey);

		return new ObjectName(getObjectNameString(DOMAIN,lhm));
	}

	/**
	 * 
	 * @param domain
	 * @param lhm
	 * @return
	 */
	private  String getObjectNameString(String domain,LinkedHashMap<String,String> lhm) {
	    
	    StringBuilder objectNameString = new StringBuilder();
	    //domain => domain:*
	    objectNameString.append(domain);
	    objectNameString.append(":");
		
		 //key-value => key=value;*
		for(Iterator<String> it =  lhm.keySet().iterator();it.hasNext();)
		{
			String key = it.next();
			objectNameString.append(key);
			objectNameString.append("=");
			objectNameString.append(lhm.get(key));
			if(it.hasNext()) {
			    objectNameString.append(",");
			}
	    }
	    String temp = objectNameString.toString();
	    return temp;	    
	}
}
